<template>
  <div class="service-detail-page" v-loading="loading">
    <div class="container">
      <!-- 面包屑导航 -->
      <el-breadcrumb class="breadcrumb" separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/services' }">服务列表</el-breadcrumb-item>
        <el-breadcrumb-item>{{ service.name }}</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="service-detail" v-if="service.id">
        <!-- 服务主要信息 -->
        <div class="service-main">
          <div class="service-images">
            <div class="main-image">
              <img :src="currentImage" :alt="service.name" />
            </div>
            <div class="thumbnail-list" v-if="service.images && service.images.length > 1">
              <div
                v-for="(image, index) in service.images"
                :key="index"
                class="thumbnail-item"
                :class="{ active: currentImage === image }"
                @click="currentImage = image"
              >
                <img :src="image" :alt="`${service.name} ${index + 1}`" />
              </div>
            </div>
          </div>

          <div class="service-info">
            <div class="service-header">
              <h1 class="service-title">{{ service.name }}</h1>
              <div class="service-badges">
                <el-tag v-if="service.isHot" type="danger">热门</el-tag>
                <el-tag v-if="service.isNew" type="success">新品</el-tag>
                <el-tag v-if="service.isRecommended" type="warning">推荐</el-tag>
              </div>
            </div>

            <div class="service-rating">
              <el-rate
                v-model="service.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}分"
              />
              <span class="review-count">（{{ service.reviewCount }}条评价）</span>
            </div>

            <div class="service-price">
              <span class="current-price">¥{{ service.price }}</span>
              <span v-if="service.originalPrice" class="original-price">¥{{ service.originalPrice }}</span>
              <span v-if="service.discount" class="discount-tag">{{ service.discount }}折</span>
            </div>

            <div class="service-description">
              <p>{{ service.description }}</p>
            </div>

            <div class="service-features">
              <h3>服务特色</h3>
              <div class="feature-list">
                <el-tag
                  v-for="feature in service.features"
                  :key="feature"
                  type="info"
                  class="feature-tag"
                >
                  {{ feature }}
                </el-tag>
              </div>
            </div>

            <div class="service-meta">
              <div class="meta-item">
                <span class="meta-label">处理时间：</span>
                <span class="meta-value">{{ service.processingTime }}小时</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">已售数量：</span>
                <span class="meta-value">{{ service.salesCount }}件</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">服务区域：</span>
                <span class="meta-value">{{ service.serviceArea || '全市范围' }}</span>
              </div>
            </div>

            <div class="service-actions">
              <el-button type="primary" size="large" @click="showBookingDialog">
                立即预约
              </el-button>
              <el-button size="large" @click="addToFavorites">
                <el-icon><Star /></el-icon>
                {{ service.isFavorited ? '已收藏' : '收藏' }}
              </el-button>
              <el-button size="large" @click="contactService">
                <el-icon><ChatDotRound /></el-icon>
                咨询客服
              </el-button>
            </div>
          </div>
        </div>

        <!-- 详细信息标签页 -->
        <div class="service-tabs">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="服务详情" name="details">
              <div class="service-details">
                <h3>服务介绍</h3>
                <div class="details-content" v-html="service.detailContent"></div>
                
                <h3>服务流程</h3>
                <div class="process-steps">
                  <div
                    v-for="(step, index) in service.serviceProcess"
                    :key="index"
                    class="process-step"
                  >
                    <div class="step-number">{{ index + 1 }}</div>
                    <div class="step-content">
                      <h4>{{ step.title }}</h4>
                      <p>{{ step.description }}</p>
                    </div>
                  </div>
                </div>

                <h3>注意事项</h3>
                <ul class="notice-list">
                  <li v-for="notice in service.notices" :key="notice">{{ notice }}</li>
                </ul>
              </div>
            </el-tab-pane>

            <el-tab-pane label="用户评价" name="reviews">
              <div class="service-reviews">
                <div class="review-summary">
                  <div class="rating-overview">
                    <div class="rating-score">
                      <span class="score">{{ service.rating }}</span>
                      <el-rate v-model="service.rating" disabled />
                    </div>
                    <div class="rating-stats">
                      <div
                        v-for="(count, rating) in service.ratingStats"
                        :key="rating"
                        class="rating-bar"
                      >
                        <span>{{ rating }}星</span>
                        <div class="progress-bar">
                          <div
                            class="progress-fill"
                            :style="{ width: (count / service.reviewCount * 100) + '%' }"
                          ></div>
                        </div>
                        <span>{{ count }}</span>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="review-list">
                  <div
                    v-for="review in reviews"
                    :key="review.id"
                    class="review-item"
                  >
                    <div class="review-header">
                      <div class="user-info">
                        <img :src="review.userAvatar || '/default-avatar.jpg'" :alt="review.userName" />
                        <span class="user-name">{{ review.userName }}</span>
                      </div>
                      <div class="review-meta">
                        <el-rate v-model="review.rating" disabled size="small" />
                        <span class="review-date">{{ formatDate(review.createdAt) }}</span>
                      </div>
                    </div>
                    <div class="review-content">
                      <p>{{ review.content }}</p>
                      <div v-if="review.images" class="review-images">
                        <img
                          v-for="image in review.images"
                          :key="image"
                          :src="image"
                          alt="评价图片"
                          @click="previewImage(image)"
                        />
                      </div>
                    </div>
                  </div>
                </div>

                <div class="load-more" v-if="hasMoreReviews">
                  <el-button @click="loadMoreReviews" :loading="loadingReviews">
                    加载更多评价
                  </el-button>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="常见问题" name="faq">
              <div class="service-faq">
                <el-collapse v-model="activeFaq">
                  <el-collapse-item
                    v-for="(faq, index) in service.faqs"
                    :key="index"
                    :title="faq.question"
                    :name="index"
                  >
                    <div>{{ faq.answer }}</div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 推荐服务 -->
        <div class="recommended-services" v-if="recommendedServices.length > 0">
          <h3>相关推荐</h3>
          <div class="service-grid">
            <div
              v-for="relatedService in recommendedServices"
              :key="relatedService.id"
              class="service-card"
              @click="goToService(relatedService.id)"
            >
              <img :src="relatedService.image" :alt="relatedService.name" />
              <div class="card-info">
                <h4>{{ relatedService.name }}</h4>
                <div class="card-price">¥{{ relatedService.price }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 预约对话框 -->
      <el-dialog v-model="showBooking" title="服务预约" width="500px">
        <div class="booking-form">
          <p>您正在预约：<strong>{{ service.name }}</strong></p>
          <p>服务价格：<span class="price">¥{{ service.price }}</span></p>
          <el-button type="primary" size="large" style="width: 100%;" @click="proceedToBooking">
            前往预约页面
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star, ChatDotRound } from '@element-plus/icons-vue'
import { serviceApi } from '@/services/api'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const loadingReviews = ref(false)
const showBooking = ref(false)
const activeTab = ref('details')
const activeFaq = ref([])
const currentImage = ref('')

const service = reactive({
  id: null,
  name: '',
  description: '',
  price: 0,
  originalPrice: 0,
  discount: 0,
  rating: 0,
  reviewCount: 0,
  salesCount: 0,
  processingTime: 0,
  serviceArea: '',
  images: [],
  features: [],
  isHot: false,
  isNew: false,
  isRecommended: false,
  isFavorited: false,
  detailContent: '',
  serviceProcess: [],
  notices: [],
  faqs: [],
  ratingStats: {}
})

const reviews = ref([])
const recommendedServices = ref([])
const hasMoreReviews = ref(true)

// 模拟服务详情数据
const mockServiceData = {
  1: {
    id: 1,
    name: '普通干洗服务',
    description: '适用于各类需要干洗的衣物，使用环保干洗剂，呵护衣物纤维，让您的衣物焕然一新',
    price: 25,
    originalPrice: 30,
    discount: 8.3,
    rating: 4.8,
    reviewCount: 1285,
    salesCount: 1285,
    processingTime: 24,
    serviceArea: '全市范围',
    images: ['/service-dry-clean.jpg', '/service-dry-clean-2.jpg', '/service-dry-clean-3.jpg'],
    features: ['环保干洗剂', '24小时完成', '免费取送', '专业除污', '形状保持'],
    isHot: true,
    isNew: false,
    isRecommended: true,
    isFavorited: false,
    detailContent: `
      <p>我们的普通干洗服务采用最先进的环保干洗技术，使用无毒、无害的环保干洗剂，有效去除各类污渍的同时，完美保护衣物纤维和颜色。</p>
      <p>适用范围：西装、大衣、羊毛衫、丝绸制品、皮革制品等需要干洗的衣物。</p>
      <p>我们的专业技师经过严格培训，对不同面料的处理方式了如指掌，确保您的每一件衣物都能得到最专业的护理。</p>
    `,
    serviceProcess: [
      { title: '上门取件', description: '专业师傅按约定时间上门取件，检查衣物状况' },
      { title: '分类处理', description: '根据衣物材质和污渍类型进行专业分类' },
      { title: '干洗清洁', description: '使用环保干洗剂进行深度清洁' },
      { title: '整理包装', description: '专业熨烫整理，精美包装' },
      { title: '送货上门', description: '按约定时间送货上门' }
    ],
    notices: [
      '请在预约时说明衣物的特殊要求',
      '贵重衣物建议选择高档衣物干洗服务',
      '如有特殊污渍请提前告知',
      '皮革制品需要特殊处理，可能需要额外时间'
    ],
    faqs: [
      { question: '干洗对衣物有损害吗？', answer: '我们使用的环保干洗剂对衣物无损害，反而能更好地保护衣物纤维和颜色。' },
      { question: '多久能够完成？', answer: '普通干洗服务一般24小时内完成，急件可以加急处理。' },
      { question: '如果洗坏了怎么办？', answer: '我们为每件衣物购买了保险，如因我们的原因造成损坏，将按原价赔偿。' }
    ],
    ratingStats: { 5: 800, 4: 350, 3: 100, 2: 25, 1: 10 }
  }
}

const mockReviews = [
  {
    id: 1,
    userName: '张**',
    userAvatar: '/avatar1.jpg',
    rating: 5,
    content: '服务非常好，衣服洗得很干净，师傅很准时，态度也很好。会继续使用的！',
    createdAt: '2024-12-10',
    images: ['/review1.jpg']
  },
  {
    id: 2,
    userName: '李**',
    userAvatar: '/avatar2.jpg',
    rating: 4,
    content: '整体满意，就是价格稍微贵了一点，但是质量确实不错。',
    createdAt: '2024-12-08',
    images: []
  },
  {
    id: 3,
    userName: '王**',
    userAvatar: '/avatar3.jpg',
    rating: 5,
    content: '专业度很高，我的羊绒大衣洗得很好，没有变形，很满意！',
    createdAt: '2024-12-05',
    images: ['/review2.jpg', '/review3.jpg']
  }
]

const fetchServiceDetail = async () => {
  try {
    loading.value = true
    const serviceId = route.params.id
    
    // 实际项目中应调用API
    // const response = await serviceApi.getServiceDetail(serviceId)
    // Object.assign(service, response.data)
    
    // 模拟API响应
    const mockData = mockServiceData[serviceId]
    if (mockData) {
      Object.assign(service, mockData)
      currentImage.value = service.images[0]
    }
    
  } catch (error) {
    ElMessage.error('获取服务详情失败')
    console.error('获取服务详情失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchReviews = async () => {
  try {
    // 实际项目中应调用API获取评价
    reviews.value = mockReviews
  } catch (error) {
    console.error('获取评价失败:', error)
  }
}

const fetchRecommendedServices = async () => {
  try {
    // 实际项目中应调用API获取推荐服务
    recommendedServices.value = [
      { id: 2, name: '高档衣物干洗', price: 68, image: '/service-luxury.jpg' },
      { id: 3, name: '家居用品清洗', price: 45, image: '/service-home.jpg' },
      { id: 4, name: '衣物熨烫整理', price: 15, image: '/service-iron.jpg' }
    ]
  } catch (error) {
    console.error('获取推荐服务失败:', error)
  }
}

const showBookingDialog = () => {
  showBooking.value = true
}

const proceedToBooking = () => {
  // 跳转到预约页面或商家列表
  router.push('/merchants')
  showBooking.value = false
}

const addToFavorites = () => {
  service.isFavorited = !service.isFavorited
  ElMessage.success(service.isFavorited ? '收藏成功' : '取消收藏成功')
}

const contactService = () => {
  router.push('/contact')
}

const loadMoreReviews = async () => {
  try {
    loadingReviews.value = true
    // 模拟加载更多评价
    await new Promise(resolve => setTimeout(resolve, 1000))
    hasMoreReviews.value = false
  } catch (error) {
    console.error('加载更多评价失败:', error)
  } finally {
    loadingReviews.value = false
  }
}

const previewImage = (image) => {
  // 实现图片预览功能
  console.log('预览图片:', image)
}

const goToService = (serviceId) => {
  router.push(`/services/${serviceId}`)
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

onMounted(() => {
  fetchServiceDetail()
  fetchReviews()
  fetchRecommendedServices()
})
</script>

<style scoped>
.service-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb {
  background: white;
  padding: 12px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.service-detail {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.service-main {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  padding: 30px;
}

.service-images {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.main-image {
  width: 100%;
  height: 400px;
  border-radius: 8px;
  overflow: hidden;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-list {
  display: flex;
  gap: 8px;
}

.thumbnail-item {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s ease;
}

.thumbnail-item.active {
  border-color: #409eff;
}

.thumbnail-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.service-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.service-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.service-badges {
  display: flex;
  gap: 8px;
}

.service-rating {
  display: flex;
  align-items: center;
  gap: 12px;
}

.review-count {
  color: #666;
  font-size: 14px;
}

.service-price {
  display: flex;
  align-items: center;
  gap: 12px;
}

.current-price {
  font-size: 32px;
  font-weight: 600;
  color: #e6a23c;
}

.original-price {
  font-size: 18px;
  color: #999;
  text-decoration: line-through;
}

.discount-tag {
  background: #ff4757;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.service-description p {
  color: #666;
  line-height: 1.6;
  font-size: 16px;
}

.service-features h3 {
  font-size: 18px;
  margin-bottom: 12px;
  color: #333;
}

.feature-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.feature-tag {
  padding: 6px 12px;
}

.service-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-label {
  font-weight: 500;
  color: #666;
  width: 80px;
}

.meta-value {
  color: #333;
}

.service-actions {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.service-tabs {
  padding: 30px;
  border-top: 1px solid #f0f0f0;
}

.service-details {
  max-width: 800px;
}

.service-details h3 {
  font-size: 18px;
  margin: 24px 0 12px 0;
  color: #333;
}

.details-content {
  line-height: 1.6;
  color: #666;
  margin-bottom: 24px;
}

.process-steps {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}

.process-step {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.step-number {
  width: 32px;
  height: 32px;
  background: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  flex-shrink: 0;
}

.step-content h4 {
  margin: 0 0 4px 0;
  color: #333;
}

.step-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.notice-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.notice-list li {
  padding: 8px 0;
  color: #666;
  border-bottom: 1px solid #f0f0f0;
}

.notice-list li:before {
  content: '•';
  color: #409eff;
  margin-right: 8px;
}

.service-reviews {
  max-width: 800px;
}

.review-summary {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.rating-overview {
  display: flex;
  gap: 40px;
  align-items: center;
}

.rating-score {
  text-align: center;
}

.score {
  display: block;
  font-size: 48px;
  font-weight: 600;
  color: #ff9900;
  margin-bottom: 8px;
}

.rating-stats {
  flex: 1;
}

.rating-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #ff9900;
  transition: width 0.3s ease;
}

.review-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.review-item {
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-info img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.user-name {
  font-weight: 500;
  color: #333;
}

.review-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.review-date {
  font-size: 12px;
  color: #999;
}

.review-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 12px;
}

.review-images {
  display: flex;
  gap: 8px;
}

.review-images img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.service-faq {
  max-width: 800px;
}

.recommended-services {
  padding: 30px;
  border-top: 1px solid #f0f0f0;
}

.recommended-services h3 {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
}

.service-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.service-card {
  background: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.service-card:hover {
  transform: translateY(-2px);
}

.service-card img {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.card-info {
  padding: 12px;
}

.card-info h4 {
  font-size: 14px;
  margin: 0 0 8px 0;
  color: #333;
}

.card-price {
  font-size: 16px;
  font-weight: 600;
  color: #e6a23c;
}

.booking-form {
  text-align: center;
  padding: 20px 0;
}

.booking-form p {
  margin-bottom: 16px;
  font-size: 16px;
}

.booking-form .price {
  font-size: 24px;
  font-weight: 600;
  color: #e6a23c;
}

@media (max-width: 768px) {
  .service-main {
    grid-template-columns: 1fr;
    padding: 20px;
  }
  
  .service-actions {
    flex-direction: column;
  }
  
  .rating-overview {
    flex-direction: column;
    gap: 20px;
  }
  
  .review-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .service-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style> 